package hotel.quartz.oversea.job.task;

import com.alibaba.fastjson.JSON;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.enums.MtHotelEnums;
import hotel.base.oversea.utils.Result;
import hotel.quartz.oversea.vo.meituan.MtHotelOrderBookingDealingDto;
import hotel.quartz.oversea.vo.meituan.MtHotelOrderQueryDetailOrderBaseInfoVo;
import hotel.quartz.oversea.util.JobRestTemplateUtils;
import hotel.quartz.oversea.vo.meituan.MtHotelOrderQueryDetailVo;
import hotel.quartz.oversea.vo.meituan.MtHotelOrderQueryParamVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class MeituanHotelOrderQueryTask {
    @Autowired
    private MeituanHotelOrderQueryCheckOneOrderTask meituanHotelOrderQueryCheckOneOrderTask;
    @Autowired
    private RestTemplate restTemplate;
    private String timestamp;
    private int queryNumber=20;//每次请求查询订单数量
    void setTimestamp(String timestamp){
        this.timestamp = timestamp;
    }
    //@Async 标识这个方法异步执行，可返回void或Future
    @Async
    public void executeOrderQuery(String timestamp, List<MtHotelOrderBookingDealingDto> dtoIds, String orderQueryUrl) throws Exception {
        setTimestamp(timestamp);
        log.info("Meituan Hotel Query Job {} >>>>>>>>MeituanHotelOrderQueryTask 酒店主动查询订单定时器 进入异步线程task,执行时间: {}",timestamp, cn.hutool.core.date.DateUtil.now());
        log.info("Meituan Hotel Query Job MeituanHotelOrderQueryTask {} 酒店主动查询订单定时器进入方法 requestSaveWaitDataApi:{}",timestamp,dtoIds);

        //查询上游订单实时状态
        if(null != dtoIds && dtoIds.size()>0){
            List<MtHotelOrderBookingDealingDto> thisDtoIds = new ArrayList<>();
            for (int i = 0; i < dtoIds.size(); i++) {
                MtHotelOrderBookingDealingDto dto = dtoIds.get(i);
                if((i+1)%queryNumber!=0){
                    thisDtoIds.add(dto);
                }else{
                    queryApi(orderQueryUrl,thisDtoIds);
                    thisDtoIds = new ArrayList<>();
                    try {
                        Thread.currentThread().sleep(2000);
                    }catch (Exception e){
                        log.error(e.getMessage(),e);
                    }
                }
                if(i == dtoIds.size()-1){
                    if(null != thisDtoIds && thisDtoIds.size()>0){
                        queryApi(orderQueryUrl,thisDtoIds);
                    }
                }
            }

        }
        log.info("Meituan Hotel Query Job {} >>>>>>>>MeituanHotelOrderQueryTask  酒店主动查询订单定时器 进入异步线程task,结束时间: {},{}",timestamp, cn.hutool.core.date.DateUtil.now());
    }
   /* @Async
    public Future<String> doTaskTwo() throws Exception {
        System.out.println("task2");
        return new AsyncResult<>("任务一完成");
    }*/

    /**
     * 数据库中处理中的订单 查询上游订单详情接口
     *
     * @param orderQueryUrl
     * @param dtoIds
     */
    private  void queryApi(String orderQueryUrl,List<MtHotelOrderBookingDealingDto> dtoIds){
        log.error("Meituan Hotel Query Job MeituanHotelOrderQueryTask {} 美团订单主动查询，已获取到数据库中处理中的订单 查询上游订单详情接口 : {},{}",timestamp,orderQueryUrl, JSON.toJSONString(dtoIds));
        List<MtHotelOrderQueryParamVo> pVo = new ArrayList<>();
        for (MtHotelOrderBookingDealingDto v:dtoIds){
            MtHotelOrderQueryParamVo p = new MtHotelOrderQueryParamVo();
            p.setMtOrderId(Long.valueOf(v.getMtOrderId()));
            p.setDistributorOrderId(v.getMtDistributorOrderId());
            pVo.add(p);
        }
        Map map = new HashMap();
        map.put("mtHotelOrderQueryParamVoList", JSON.toJSONString(pVo));
        //发起请求
        Result response = JobRestTemplateUtils.post(orderQueryUrl, JSON.toJSONString(map),restTemplate);
        if(response.getCode()== CommonConstants.SUCCESS){
            Map<String,String> idsMap = new HashMap<>();
            for (MtHotelOrderBookingDealingDto dto:dtoIds){
                idsMap.put(dto.getMtOrderId(),dto.getMtDistributorOrderId());
            }
            //判断订单状态，处理相关业务，这边和异步通知方法那边的处理一样
            List<MtHotelOrderQueryDetailVo> details = JSON.parseArray(response.getData().toString(), MtHotelOrderQueryDetailVo.class);
            int i = 0;
            for (MtHotelOrderQueryDetailVo vo:details){
                Integer orderStatus = vo.getBaseInfo().getOrderStatus();
                if(MtHotelEnums.orderStateEnum.CANCELING.getCode()!=orderStatus && MtHotelEnums.orderStateEnum.BOOKING.getCode()!=orderStatus){
                    //已经不是确定中和取消中状态订单则为订单发生了状态改变，需要判断处理！！！！ 当不是处理中时  调用内部外放接口处理订单状态！
                    MtHotelOrderQueryDetailOrderBaseInfoVo detail = vo.getBaseInfo();
                    Long thisMtOrderId = vo.getAptInfo().getMtOrderId();
                    String hhbOrderId = idsMap.get(String.valueOf(thisMtOrderId));
                    meituanHotelOrderQueryCheckOneOrderTask.checkOneOrder(vo,detail.getOrderStatus(),String.valueOf(thisMtOrderId),hhbOrderId,timestamp+"_"+i);
                    i++;
                }else{
                    log.error("Meituan Hotel Query Job MeituanHotelOrderQueryTask {} 美团订单主动查询，循环订单，查询上游订单详情接口,该订单状态还未改变还是处理中 : {},{}",timestamp,orderQueryUrl, JSON.toJSONString(vo));
                }

            }
        }else{
            log.error("Meituan Hotel Query Job MeituanHotelOrderQueryTask {} 酒店主动查询订单定时器进入方法 requestSaveWaitDataApi 发起请求 返回失败: {},{},{}",timestamp,orderQueryUrl, JSON.toJSONString(map),response);
        }
    }

}
